/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int n1=0,n2=0;
        ListNode* h1=headA,*h2=headB;
        while(h1)
        {
            n1++;
            h1=h1->next;
        }
        while(h2)
        {
            n2++;
            h2=h2->next;
        }
        h1=headA,h2=headB;
        if(n1>n2)
        {
            int t=n1-n2;
            while(t--){
                h1=h1->next;
            }
            bool flg=false;
            while(h1 && h2 && h1->val!=h2->val)
            {
                h1=h1->next;
                h2=h2->next;
            }
            if(h1 && h2)
            {
                return h1;
            }
            else{
                return nullptr;
            }
        }
        else{
            int t=n2-n1;
            while(t--){
                h2=h2->next;
            }
            bool flg=false;
            while(h1 && h2 && h1->val!=h2->val)
            {
                h1=h1->next;
                h2=h2->next;
            }
            if(h1 && h2)
            {
                return h1;
            }
            else{
                return nullptr;
            }            
        }
    }
};
